set.seed(1234567)

effect_size <- 0.333

design <-
  declare_model(
    units = add_level(
      N = 18,
      U_unit = rnorm(N)
      # place fixed effects have variance = 1
    ),
    periods = add_level(
      N = 18,
      time = 1:max(periods),
      U_time = rnorm(N),
      # time fixed effects have variance = 1
      nest = FALSE
    ),
    unit_period = cross_levels(
      by = join(units, periods),
      U = rnorm(N),
      # idiosyncratic disturbance has variance = 1
      potential_outcomes(
        Y ~ scale(U_unit + U_time + U) + effect_size * Z
        # untreated potential outcomes have scaled variance of 1
      )
    )
  ) +
  declare_assignment(
    wave = cluster_ra(clusters = units, conditions = 1:max(periods)),
    Z = if_else(time >= wave, 1, 0)
  ) +
  declare_inquiry(ATE = mean(Y_Z_1 - Y_Z_0), subset = time < max(time)) +
  declare_measurement(Y = reveal_outcomes(Y ~ Z)) +
  declare_estimator(Y ~ Z, fixed_effects = ~ periods + units,
                    clusters = units,
                    subset = time < max(time),
                    inquiry = "ATE", label = "TWFE")

draw_estimates(design)


diagnosands <- declare_diagnosands(power = mean(p.value <= 0.05))

diagnosis <-
  diagnose_design(design,
                  sims = 10000)
diagnosis <- diagnosis$diagnosands_df %>%
  select(inquiry, estimator, bias, rmse,power )

names(diagnosis) <- c("Estimand",
                      "Estimator",
                      "Bias",
                      "RMSE",
                      "Power")

sink(file = "03_tables/power_calcs.tex")
print(kable(diagnosis, format = "latex", digits = 3))
sink()
